<?php
include 'db.php';

class REST_API {
  public $_request = array();
  private $_db = NULL;
  private $api_key = "4l7gUYPCRhaioPCjnCNFAy06VhQFa47RElCUndsBeZvQh2PjHI";

  //private $_tzone = new DateTimezone('EST');

  public function __construct() {
    $mysqli = $this->dbConnect();
    switch($_SERVER['REQUEST_METHOD']) {
      case "POST":
        $this->_request = $this->cleanInputs($_POST);
        //echo $this->_request["blog"] . "<br/>";
        $blog = $this->cleanData($this->_request["blog"]);
        $this->addBlog($mysqli,$blog);
    	  $qry_str = "SELECT sname FROM subscribed";
    	  $result = mysqli_query($mysqli, $qry_str);
    	  if (!mysqli_num_rows($result)) {} else {
    	    while ($row = mysqli_fetch_array($result)){
    	      $posts_info = $this->getPostsInfo($row["sname"]);
            foreach($posts_info as $post_info) {
              dbUpdate($post_info,$mysqli);
            }
    	    }
        }
        break;
      case "GET":
        $path = $_SERVER["REQUEST_URI"];
        $parsed = explode("/", $path);
        $limit = $this->cleanData($_GET["limit"]);
        $order = $this->cleanData($_GET["order"]);
        $index = array_search('blog',$parsed);
        if ($index != false) {
          $parsed = array_slice($parsed,$index+1);
          $base_hostname = $parsed[0];
          $json_result = $this->getBlogLike($mysqli, $base_hostname, $limit, $order);
        } else {
          $index = array_search('blogs',$parsed);
          if ($index != false) {
            $parsed = array_slice($parsed,$index+1);
            $json_result = $this->getBlogLike($mysqli, '', $limit, $order);
          } else {}
        }
    	  $qry_str = "SELECT sname FROM subscribed";
    	  $result = mysqli_query($mysqli, $qry_str);
    	  if (!mysqli_num_rows($result)) {} else {
    	    while ($row = mysqli_fetch_array($result)){
    	      $posts_info = $this->getPostsInfo($row["sname"]);
            foreach($posts_info as $post_info) {
              dbUpdate($post_info,$mysqli);
            }
    	    }
        }
        $this->response($json_result, 200);
        break;
      case "PUT":
        echo "haha, it works!<br/>";
        break;
      default:
        $this->response('',406);
        break;
    }
  }

  private function dbConnect() {
    // If the db is null, connect to the database
    if (!$this->_db) {
      $mysqli = new mysqli("dbsrv1.cdf.toronto.edu", "c3wujunq", "vishoosu", "csc309h_c3wujunq", 3306);
      if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ")" . $mysqli->connect_error;
      }
    }
    return $mysqli;
  }
  
  private function addBlog($mysqli,$blog) {
    if (isset($blog)) {
      $blog = strtolower(trim(str_replace("/","",$blog)));
    }

    $qry_str = "SELECT * FROM subscribed WHERE sname = '" . $blog . "'";
    $result = mysqli_query($mysqli, $qry_str);
    if (!mysqli_num_rows($result)) {
      $qry_str = "INSERT INTO subscribed (sname) VALUES ('" . $blog . "')";  
      if (insert_update($mysqli, $qry_str) == 1) {;
    	$this->reponse('',200);
      }
    }    
  }
  
  private function getPostsInfo($blog) {

    $json = file_get_contents("http://api.tumblr.com/v2/blog/" . $blog . "/likes?api_key=" . $this->api_key);
    $json = json_decode($json);
    
    $cur_time = date("Y-m-d H:i:s");
    
    $posts_info = array();
    foreach ($json->response->liked_posts as $liked_post ) {
      $post_time = $this->processTime($liked_post->date, new DateTimezone('EST'));
      $text = $this->getText($liked_post);
      
      if ($liked_post->type == "photo") {
        $image = $liked_post->photos[0]->alt_sizes[0]->url;
      } else {
        $image = $liked_post->image_permalink;
      }
      
      $post_info = array (
        "blog" => $blog,
        "id" => $liked_post->id,
        "url" => $liked_post->post_url,
        "text" => $text,
        "image" => $image,
        "date" => $post_time,
        "last_track" => $cur_time,
        "last_count" => $liked_post->note_count
      );

      array_push($posts_info, $post_info);
    }

    return $posts_info;
  }
  
  private function processTime($temp_timestamp, $timezone) {
    $temp_timestamp = new DateTime($temp_timestamp);
    $temp_timestamp  = $temp_timestamp->setTimezone($timezone);
    $temp_timestamp = $temp_timestamp->format("Y-m-d H:i:s");
    return $temp_timestamp;
  }
  
  private function getText($liked_post) {
    switch($liked_post->type){
      case "text":
      case "chat":
        $text = strip_tags($liked_post->title . ". " . $liked_post->body);
        break;
      case "photo":
      case "audio":
      case "video":
        $text = strip_tags($liked_post->caption);
        break;
      case "link":
        $text = strip_tags($liked_post->title . ". " . $liked_post->description);
        break;
      case "quote":
        $text = strip_tags($liked_post->text);
        break;
      case "answer":
        $text = strip_tags($liked_post->question . ". " . $liked_post->answer);
        break;
     }
     return $text;
}

  private function getBlogLike($mysqli, $blog, $limit, $order) {
    if ($limit === NULL) {
      $temp = '';
    } else {
      $temp = " limit " . $limit;
    }
    
    if ($blog != '') {
      $qry_str = "SELECT * FROM subscribed WHERE sname LIKE '" . $blog . "'"; 
      $qry_result = mysqli_query($mysqli, $qry_str);
      if (!mysqli_num_rows($qry_result)) {
        $this->response('The blog is not subscribed!', 406);
        return;
      }
      if ($order == "recent") {
        $qry_str = "SELECT distinct I.PID, url, img, post_time, last_track, last_count, sname FROM subscribed S, info I, relation R WHERE S.SID = R.SID AND I.PID = R.PID AND S.sname LIKE '" . $blog . "' ORDER BY timestamp(post_time) desc" . $temp;
      } else {
        $qry_str = "SELECT R.PID, T.inc, ttime, url, img, post_time, last_track, last_count, sname FROM subscribed S, info I, relation R, tracking T WHERE S.SID = R.SID AND I.PID = R.PID AND T.TID = R.TID AND S.sname LIKE '" . $blog . "' AND (T.ttime > date_sub(now(),interval 1 hour)) ORDER BY T.inc DESC" . $temp;
      }
    } else {
      if ($order == "recent") {
        $qry_str = "SELECT distinct I.PID, url, img, post_time, last_track, last_count, sname FROM subscribed S, info I, relation R WHERE S.SID = R.SID AND I.PID = R.PID ORDER BY timestamp(post_time) desc" . $temp;
      } else {
        $qry_str = "SELECT distinct R.PID, T.inc, ttime, url, img, post_time, last_track, last_count, sname FROM subscribed S, info I, relation R, tracking T WHERE S.SID = R.SID AND I.PID = R.PID AND T.TID = R.TID AND (T.ttime > date_sub(now(),interval 1 hour)) ORDER BY T.inc DESC" . $temp;
      }
    }
    
    $json = array();
    $qry_result = mysqli_query($mysqli, $qry_str);
    $data = array();
    if (!mysqli_num_rows($qry_result)) {
    } else {
      while($row = mysqli_fetch_array($qry_result)) {
        array_push($data, $row);
      }
    }
    
    foreach($data as $element) {
      
      // Get text information.
      $text = "";
      $text_str = "SELECT contents from text where PID = " . $element["PID"];
      $qry_result = mysqli_query($mysqli, $text_str);
      if (!mysqli_num_rows($qry_result)) {
      } else {
        while($row = mysqli_fetch_array($qry_result)) {
          $text = $text . $row["contents"];
        }
      }
      
      // Get tracking information.
      $tracking = array();
      $tracking_str = "SELECT ttime as timestamp, seq as sequence, inc as increment, cnt as count from relation R, tracking T WHERE T.TID = R.TID AND R.PID = " . $element["PID"];
      $track_result = mysqli_query($mysqli, $tracking_str);
      if (!mysqli_num_rows($track_result)) {} else {
        while($row = mysqli_fetch_object($track_result)) {
          array_push($tracking, $row);
        }
      }
      
      // Creating sub json array
      $subjson = array('url'=>$element['url'], 'text'=>iconv('UTF-8','ASCII//TRANSLIT', $text), 'image'=>$element['img'], 'date'=>$element['post_time'], 'last_track'=>$element["last_track"], 'last_count'=>$element['last_count'], 'tracking'=>$tracking);
      array_push($json, $subjson);
    }
    
    // Create json.
    $temp = array('trending'=>$json, 'order'=>$order, 'limit'=>$limit);
    $json_str = json_encode($temp);
    return $json_str;
  }
  
  private function cleanData($data) {
    if (isset($data)) {
      $data = strtolower(trim(str_replace("/","",$data)));
    }
    return $data;
  }

  private function cleanInputs($data) {
    $clean_input = array();
        if(is_array($data)){
            foreach($data as $k => $v){
                $clean_input[$k] = $this->cleanInputs($v);
            }
        }else{
            if(get_magic_quotes_gpc()){
                $data = trim(stripslashes($data));
            }
            $data = strip_tags($data);
            $clean_input = trim($data);
        }
        return $clean_input;
  }

  /* Response to the client
  */
  public function response($data, $status) {
    # Set http header
    header("HTTP/1.1 " . $status);
    header("Content-Type: application/json");
    echo $data;
  }
}

$api = new REST_API;
?>